from django.shortcuts import render, HttpResponse, redirect
import os
from django.core.paginator import Paginator
from blog.settings import BASE_DIR
from .models import Author, Blog


# Create your views here.


# 添加作者
def addauthor(request):
    if request.method == 'GET':
        return render(request, 'addauthor.html')
    if request.method == "POST":
        name = request.POST.get('name')
        icon = request.FILES.get('icon')
        with open(os.path.join(BASE_DIR, 'static', str(icon)), 'wb') as f:
            for i in icon:
                f.write(i)
        phone = request.POST.get('phone')
        email = request.POST.get('email')
        dates = Author(name=name, icon=str(icon), phone=phone, email=email)
        dates.save()
        return redirect('showauthor')


# 展示作者
def showauthor(request):
    dates = Author.objects.all()
    page = request.GET.get('page', '1')
    p = Paginator(dates, 2)
    nowpage = p.get_page(page)
    sum = p.num_pages
    nextpage = nowpage.number + 1
    lastpage = nowpage.number - 1
    return render(request, 'showauthor.html',
                  {'nowpage': nowpage, 'sum': sum, 'nextpage': nextpage, 'lastpage': lastpage})


# 删除作者
def delauthor(request, id):
    author = Author.objects.get(id=id)
    author.delete()
    return redirect('showauthor')


# 添加博客
def addblog(request):
    if request.method == 'GET':
        authors = Author.objects.all()
        return render(request, 'addblog.html', {'authors': authors})
    if request.method == "POST":
        title = request.POST.get('title')
        content = request.POST.get('content')
        author = request.POST.get('author')
        Blog.objects.create(title=title, content=content, author_id=author)
        return HttpResponse('666')


# 反向查询
def search(request, id):
    blogs = Author.objects.get(id=id).blog_set.all()
    return render(request, 'search.html', {'blogs': blogs})


# 展示博客
def showblog(request):
    blogs = Blog.objects.all()
    return render(request, 'showblog.html', {'blogs': blogs})
